package org.miyuki4j.cfgtool.app.web;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import lombok.extern.slf4j.Slf4j;
import org.miyuki4j.cfgtool.*;
import org.miyuki4j.cfgtool.exception.CommandParseException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

/**
 * @Desc
 * @Author miyuki4j
 * @Date 2025/7/28/星期一 19:01
 * @Version 1.0
 */
@Controller
@Slf4j
public class MainCfgController {

    @RequestMapping("/index")
    public String index() {
        return "index";
    }

    @RequestMapping("/done")
    @ResponseBody
    public String done() {
        log.info("done");
        CfgAppKeeper.done();
        return "done";
    }

    @RequestMapping("/command")
    @ResponseBody
    public String command(@RequestParam(name = "args") String args) throws Exception {
        try {
            Commands.run(args.split(" "));
            return "execute success";
        } catch (Exception e) {
            return String.format("execute failed, args:%s error:%s", args, e);
        }
    }

    @RequestMapping("/code_generate")
    @ResponseBody
    public Map<String, Object> codeGenerate(@RequestParam Map<String, String> params) {
        params.remove("code_generate_response");

        log.info("收到参数：\n{}", JSON.toJSONString(params, JSONWriter.Feature.PrettyFormat));
        try {
            Commands.run(parseArgs(Command.CommandEnum.CODE_GENERATE, params));
        } catch (Exception e) {
            log.error("代码生成失败", e);
            return createResponse(false, ExceptionUtil.getStackTrace("代码生成失败", e));
        }
        return createResponse(true, "代码生成成功^_^");
    }

    @RequestMapping("/data_export")
    @ResponseBody
    public Map<String, Object> dataExport(@RequestParam Map<String, String> params) {
        params.remove("data_export_response");
        log.info("收到参数：\n{}", JSON.toJSONString(params, JSONWriter.Feature.PrettyFormat));
        try {
            Commands.run(parseArgs(Command.CommandEnum.EXPORT_DATA, params));
        } catch (Exception e) {
            log.error("数据导出失败", e);
            createResponse(false, ExceptionUtil.getStackTrace("数据导出失败", e));
        }
        return createResponse(true, "数据导出成功^_^");
    }

    private String[] parseArgs(Command.CommandEnum cmd, Map<String, String> params) {
        List<String> args = new ArrayList<>();
        args.add(cmd.getArg());
        for (TableConfig.ConfigKeyEnum configKey : cmd.getConfigKeys()) {
            if (!params.containsKey(configKey.getValue())) {
                continue;
            }
            String value = params.get(configKey.getValue());
            if (StringUtils.isBlank(value)) {
                if (configKey.isRequired()) {
                    throw new CommandParseException("参数 " + configKey.getArg() + " 不能为空");
                }
                continue;
            }
            args.add(configKey.getArg(value));
        }
        for (Map.Entry<String, String> entry : params.entrySet()) {
            args.add("--" + entry.getKey() + "=" + entry.getValue());
        }
        return args.toArray(new String[0]);
    }

    Map<String, Object> createResponse(boolean success, String msg) {
        Map<String, Object> resp = new LinkedHashMap<>();
        resp.put("success", success);
        resp.put("msg", msg);
        return resp;
    }
}
